package graphic.dialogs;

import graphic.MainFrame;
import graphic.mycomponents.TextChecked;

import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import utility.GraphicUtilsFactory;
import dbms.DBAddingFunctions;

public class ChangeUserPasswordDialog extends AbstractDialog {

	TextChecked newPassword;
	TextChecked newPasswordConf;
	
	JLabel userIdLabel;
	String userId;
	
	public ChangeUserPasswordDialog(String userId)
	{
		super("Change User Password", "Change", 300, 300, false);
	}

	@Override
	public void initDialog()
	{
		this.newPassword = new TextChecked("", TextChecked.PASSWORD, true, false, null);
		this.newPasswordConf = new TextChecked("", TextChecked.PASSWORD, true, false, null);
		this.userIdLabel = new JLabel(this.userId, JLabel.CENTER);
		this.userIdLabel.setFont(new Font("Tahoma", Font.BOLD, 30));
		
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.newPassword, "New Password");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.newPasswordConf, "Repeat Password");
		GraphicUtilsFactory.setTitleAndBorderToComponent(this.userIdLabel, "User Id");		
	}
	
	@Override
	public void createPanel()
	{
		super.setPanel(new JPanel(new GridBagLayout()));
		
		JPanel panel = super.getPanel(); 
		
		GridBagConstraints c = new GridBagConstraints();
		c.insets = new Insets(5, 10, 5, 10);
		c.fill = GridBagConstraints.BOTH;
		c.anchor = GridBagConstraints.CENTER;
		
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 2;
		panel.add(this.userIdLabel, c);
		
		c.gridx = 0;
		c.gridy = 1;
		panel.add(this.newPassword, c);
		
		c.gridx = 0;
		c.gridy = 2;
		panel.add(this.newPasswordConf, c);
		
		c.gridx = 0;
		c.gridy = 3;
		c.gridwidth = 1;
		panel.add(super.getOkButton(), c);
		
		c.gridx = 1;
		c.gridy = 3;
		panel.add(super.getExitButton(), c);
	}
	
	@Override
	public boolean checkOkFunction() {

		if(!this.newPassword.isChecked() || !this.newPasswordConf.isChecked() ||
				!this.newPassword.getText().equals(this.newPasswordConf.getText()))
		{
			JOptionPane.showMessageDialog(this, "The Passwords are not Equal!", "Error Changing User Password!", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
		return true;
	}

	@Override
	public void okFunction()
	{
		if(DBAddingFunctions.setUserPassword(this.userId, this.newPassword.getText()))
		{
			super.dispose();
			MainFrame.getInstance().showMessage("Password Changed!", JOptionPane.INFORMATION_MESSAGE);	
		} else
			MainFrame.getInstance().showMessage("Error While Changing User Password!", JOptionPane.ERROR_MESSAGE);	
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}
}
